package net.maku.system.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import net.maku.framework.common.exception.ServerException;
import net.maku.framework.common.utils.Result;
import net.maku.framework.operatelog.annotations.OperateLog;
import net.maku.framework.operatelog.enums.OperateTypeEnum;
import net.maku.storage.service.StorageService;
import net.maku.system.vo.SysFileUploadVO;
import org.apache.commons.fileupload2.core.DiskFileItem;
import org.apache.commons.fileupload2.core.DiskFileItemFactory;
import org.apache.commons.fileupload2.jakarta.servlet6.JakartaServletFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItemFactory;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.File;
import java.io.InputStream;

/**
 * 文件上传
 *
 * @author 阿沐 babamu@126.com
 * <a href="https://maku.net">MAKU</a>
 */
@RestController
@RequestMapping("sys/file")
@Tag(name = "文件上传")
@AllArgsConstructor
public class SysFileUploadController {
    private final StorageService storageService;

    @PostMapping("upload")
    @Operation(summary = "上传")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public Result<SysFileUploadVO> upload(HttpServletRequest request) throws Exception {

        if (JakartaServletFileUpload.isMultipartContent(request)) {
            DiskFileItemFactory factory = DiskFileItemFactory.builder().get();
            JakartaServletFileUpload<DiskFileItem, DiskFileItemFactory> upload = new JakartaServletFileUpload<DiskFileItem, DiskFileItemFactory>(factory);
            upload.getItemIterator(request).forEachRemaining(item -> {
                String name = item.getFieldName();
                InputStream stream = item.getInputStream();
                if (item.isFormField()) {
//                    System.out.println("Form field " + name + " with value "
//                            + Streams.asString(stream) + " detected.");
                } else {
//                    System.out.println("File field " + name + " with file name "
//                            + item.getName() + " detected.");
                    // Process the input stream
//        ...
                }
            });


//            JakartaServletFileUpload upload = new JakartaServletFileUpload(request);
//            String uploadPath = getServletContext().getRealPath("")
//                    + File.separator + UPLOAD_DIRECTORY;
//            File uploadDir = new File(uploadPath);
//            if (!uploadDir.exists()) {
//                uploadDir.mkdir();
//            }
            //...
        }

//        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//        FileUpload fileUpload = new FileUpload();
//        fileUpload.setFileItemFactory(diskFileItemFactory);
//        fileUpload.parseRequest(request.get);


//        if (file.isEmpty()) {
//            return Result.error("请选择需要上传的文件");
//        }
//
//        // 上传路径
//        String path = storageService.getPath(file.getOriginalFilename());
//        // 上传文件
//        String url = storageService.upload(file.getBytes(), path);
//
//        SysFileUploadVO vo = new SysFileUploadVO();
//        vo.setUrl(url);
//        vo.setSize(file.getSize());
//        vo.setName(file.getOriginalFilename());
//        vo.setPlatform(storageService.properties.getConfig().getType().name());

        return Result.ok(null);
    }

    @PostMapping("uploads")
    @Operation(summary = "上传")
    @OperateLog(type = OperateTypeEnum.INSERT)
    public SysFileUploadVO uploads(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new ServerException("请选择需要上传的文件");
        }
        if (!file.getOriginalFilename().endsWith("txt")){
            throw new ServerException("不允许上传其他格式的文件");
        }

        // 上传路径
        String path = storageService.getPath(file.getOriginalFilename());
        // 上传文件
        String url = storageService.upload(file.getBytes(), path);

        SysFileUploadVO vo = new SysFileUploadVO();
        vo.setUrl(url);
        vo.setName(file.getOriginalFilename());

        return null;
    }
}
